import json
import random
import re

from django import http
from django.contrib.auth import authenticate
from django.db import DatabaseError
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User
from libs.aliyun.sms import send_sms
from utils import constants
from utils.response_code import RETCODE


class UsersView(View):
    def get(self, request):
        return render(request, 'message.html')


class Register2View(View):
    '''注册'''

    def get(self, request):
        return render(request, 'register2.html')

    def post(self, request):

        # sms_code = request.POST.get('sms_code')
        # 链接redis

        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        # mobile = request.POST.get('mobile')
        redis_conn = get_redis_connection('mobile')
        # 从redis获取验证码
        try:
            mobile = redis_conn.randomkey()
            # mobile = mobile[1]
            mobile = mobile.decode()
            print(mobile)
        except Exception as e:
            return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '手机号不存在'})

        if not all([username, nickname, password, password2, mobile]):
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '缺少参数'})
        # print(mobile)
        # print(sms_code)
        print(11111111)

        # 保存注册数据
        try:
            user = User.objects.create_user(username=username, password=password, nickname=nickname, mobile=mobile)
        except DatabaseError:
            return render(request, 'register2.html', {'register_errmsg': '注册失败'})

        return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '注册成功'})


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        """
        实现登录逻辑
        :param request: 请求对象
        :return: 登录结果
        """
        # 接收参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        # print(mobile)
        if not all([username, password]):
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '缺少参数'})

        # # 判断用户名是否是5-20个字符
        # if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
        #     # return http.HttpResponseBadRequest('请输入正确的用户名或手机号')
        #     return render(request, 'login.html', {'account_errmsg': '请输入正确的用户名或手机号'})
        #
        # # 判断密码是否是8-20个数字
        # if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
        #     # return http.HttpResponseBadRequest('密码最少8位，最长20位')
        #     return render(request, 'login.html', {'account_errmsg': '密码最少8位，最长20位'})

        # 认证登录用户
        user = authenticate(username=username, password=password)
        if user is None:
            return http.JsonResponse({'errno': RETCODE.PARAMERR, 'errmsg': '用户名或密码错误'})

        # 实现状态保持
        login(request, user)
        # 设置状态保持的周期
        # if remembered != 'on':
        #     # 没有记住用户：浏览器会话结束就过期
        #     request.session.set_expiry(0)
        # else:
        #     # 记住用户：None表示两周后过期
        #     request.session.set_expiry(None)

        # 响应登录结果
        # next = request.GET.get('next')
        # if next:
        #     response = redirect(next)
        # else:
        # try:
        #     user = User.objects.get(username=username)
        # except Exception as e:
        #     print(e)
        #     return http.JsonResponse({'errno': RETCODE.DBERR, 'errmsg': '登录失败'})
        # 登陆成功
        login(request, user=user)
        # 设置cookie
        response = http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '登录成功'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

        # 返回响应
        return response


class LogoutView(View):
    def get(self, request):
        # 退出
        # 清理session
        logout(request)

        # 退出登录,重定向到登录页
        response = redirect(reverse('index:index'))

        # 删除cookie
        response.delete_cookie('username')
        return response


class RegisterView(View):

    def get(self, request):
        return render(request, 'register.html')


class SMSCodeView(View):

    def get(self, request):
        mobile = request.GET.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_conn1 = get_redis_connection('mobile')
        redis_conn1.set(mobile, mobile)

        # 生成短信验证码：生成6位数验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码
        redis_conn.setex('%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 为了在测试期间减少短信发送，可以屏蔽发送短信功能，使用打印的方式来获取到真正的验证码值
        # 发送短信验证码
        print(mobile)
        # send_sms(mobile, sms_code)
        print(">>>>短信验证码>>>>>>", sms_code)

        # 响应结果
        response = http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '发送成功'})

        return response
